<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\facade\Db;

/**
 * 会员管理.
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    protected $relationSearch = true;

    protected $searchFields = 'id,username,nickname';
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User();
    }

    /**
     * 查看.
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $total = $this->model
                ->withJoin('group')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->withJoin('group')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
                $v['vipday'] = $v['viptime']>time()?ceil(($v['viptime'] - time())/86400):0;
            }
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 编辑.
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = false;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }


    /**
     * 编辑.
     */
    public function recharge($ids = null)
    {

        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
//            $this->token();
            $data = $this->request->post('row/a');
            Db::startTrans();
            $levelabelinfo = (new \app\admin\model\Label())->where('id', $data['level'])->find();
            if (empty($levelabelinfo)) {
                $this->error('用户等级错误');
            }
            //充值
            if ($data['opertype'] == 1) {
                $vip_time = $row['viptime'] > time() ? ($row['viptime'] + $data['vip_day'] * 86400) : (time() + $data['vip_day'] * 86400);
                $xieyi = $row['xieyi'] + $data['xieyi'];

                $result = $this->model->where('id', $row['id'])->update(['viptime' => $vip_time, 'xieyi' => $xieyi,'level'=>$levelabelinfo['id']]);
                if ($result===false) {
                    $this->error('变更用户协议或会员时长失败');
                }
                $log = [
                    'user_id' => $row['id'],
                    'before_user_level_type' => $row['level'],
                    'money' => $data['money'],
                    'before' => 0,
                    'after' => $data['money'],
                    'memo' => '',
                    'createtime' => time(),
                    'oper_type' => $data['opertype'],
                    'user_level_type' => $data['level'],
                    'level_day' => $data['vip_day'],
                    'xieyi_num' => $data['xieyi'],
                    'after_xieyi_num' => $xieyi,
                    'after_level_day' => ceil(($vip_time - time()) / 86400),
                    'admin_id'=>$this->auth->id
                ];
                $result = (new \app\admin\model\Usermoneylog())->insert($log);
                if (!$result) {
                    $this->error('添加变动记录失败');
                }
                Db::commit();
                $this->success('成功');
            } else {
                $vip_time = ($row['viptime'] - $data['vip_day'] * 86400) > time() ? ($row['viptime'] - $data['vip_day'] * 86400) : strtotime(date('Y-m-d'));

                $xieyi = $row['xieyi'] - $data['xieyi'];
                if ($xieyi < 0) {
                    $this->error('协议出现负数，不允许操作');
                }
                $result = $this->model->where('id', $row['id'])->update(['viptime' => $vip_time, 'xieyi' => $xieyi,'level'=>$levelabelinfo['id']]);
                if (!$result) {
                    $this->error('变更用户协议或会员时长失败');
                }
                $log = [
                    'user_id' => $row['id'],
                    'before_user_level_type' => $row['level'],
                    'money' => $data['money'],
                    'before' => 0,
                    'after' => $data['money'],
                    'memo' => '',
                    'createtime' => time(),
                    'oper_type' => $data['opertype'],
                    'user_level_type' => $data['level'],
                    'level_day' => $data['vip_day'],
                    'xieyi_num' => $data['xieyi'],
                    'after_xieyi_num' => $xieyi,
                    'after_level_day' => ceil(($vip_time - time()) / 86400),
                    'admin_id'=>$this->auth->id
                ];
                $result = (new \app\admin\model\Usermoneylog())->insert($log);
                if (!$result) {
                    $this->error('添加变动记录失败');
                }
                Db::commit();
                $this->success('成功');
            }

        }


        $row['vip_time'] = $row['viptime'] > time() ? ceil(($row['viptime'] - time()) / 86400) : 0;
        $row['vip_time_str'] = $row['viptime'] ? date('Y-m-d H:i:s', $row['viptime']) : '-';
        $this->view->assign('row', $row);
        return $this->view->fetch();

    }

    public function rechargerecordlist($ids=null)
    {

        $row = $this->model->get($ids);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }


}
